package com.sdhs.paas.internet.login;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdhs.paas.internet.client.RestClient;
import com.sdhs.paas.sso.sp.SsoUtil;

public class User implements IUser
{
  private static Logger log = Logger.getLogger(User.class);

  public Map getUserInfo(String uid) {
	RestTemplate restTemplate = RestClient.getClient();
//	RestTemplate restTemplate = new RestTemplate();
	//设置header
	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", uid);
	MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
	//设置参数
	TokenParam tokenParam = new TokenParam();
	tokenParam.setToken(uid);
	ObjectMapper mapper = new ObjectMapper();
	String param = "";
	try {
		param = mapper.writeValueAsString(tokenParam);
	} catch (JsonProcessingException e1) {
		return null;
	}
	HttpEntity<String> requestEntity = new HttpEntity<String>(param,headers);
	String apiGatewayUrl = SsoUtil.getValue("api_gateway_url");
	ResponseEntity<UserInfo> responseEntity = null;
//	ResponseEntity<String> responseEntity = null;
	try{
		responseEntity = restTemplate.postForEntity(apiGatewayUrl+"/api/auth/jwt/userinfoN", requestEntity, UserInfo.class);
//		responseEntity = restTemplate.postForEntity(apiGatewayUrl+"/api/auth/jwt/post",requestEntity,String.class);
	}catch(Exception e){
		log.info(e.getMessage());
		e.printStackTrace();
		return null;
	}
	UserInfo userInfo = responseEntity.getBody();
	if(userInfo == null){
		return null;
	}
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("id", userInfo.getId());
	map.put("name", userInfo.getName());
	map.put("username", userInfo.getUsername());
	map.put("roles", userInfo.getRoles());
    return map;
  }

  public boolean initUserInfo(String uid, HttpSession session)
  {
    if ((uid == null) || (session == null)) return false; 
    try
    {
      Map userInfo = getUserInfo(uid);
      if (userInfo != null) {
        session.setAttribute("UserLoginInfo", userInfo);
        session.setAttribute("uid", uid);
        return true;
      }
    } catch (NumberFormatException e) {
      log.error(e);
    }
    return false;
  }

  public boolean cleanUserInfo(HttpSession session)
  {
    if (session == null) return false;
    session.removeAttribute("UserLoginInfo");
    session.removeAttribute("uid");
    return true;
  }
}
